package com.xss.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.xss.filter.XssStringJsonDeSerializer;
import com.xss.filter.XssStringJsonSerializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;


@Configuration
public class JsonConfig implements WebMvcConfigurer {

    @Bean
    public ObjectMapper xssObjectMapper(Jackson2ObjectMapperBuilder builder) {
        ObjectMapper objectMapper = builder.createXmlMapper(false).build();
        //注入自定义的序列化工具,将@RequestBody的json格式参数做转义处理
        SimpleModule simpleModule = new SimpleModule(XssStringJsonSerializer.class.getSimpleName());
        //只对入参json进行特殊字符转义
        simpleModule.addDeserializer(String.class, new XssStringJsonDeSerializer());
        //对返回给前端的json数据(特殊字符)进行转义,这里暂时注释掉,根据具体项目考虑是否需要对返回给前端的数据进行转义
        //simpleModule.addSerializer(String.class, new XssStringJsonSerializer());
        objectMapper.registerModule(simpleModule);
        return objectMapper;
    }
}

